package org.budo.wxpay.util;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;

import org.apache.commons.codec.digest.DigestUtils;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

/**
 * @author lmw
 */
public class WxpayXmlUtil {

    /**
     * MD5 hash
     * 
     * @param key
     * @param str
     */
    public static String encodeMD5(String key, String str) {
        if (str == null || "".equals(str.trim())) {
            return null;
        }

        if (key == null || "".equals(key.trim())) {
            return DigestUtils.md5Hex(str);
        } else {
            return DigestUtils.md5Hex(key.concat(str).concat(key));
        }
    }

    /**
     * 微信支付 创建sign
     * 
     * @param characterEncoding
     * @param parameters
     * @param apiKey
     */
    @SuppressWarnings("rawtypes")
    public static String buildSign(String characterEncoding, SortedMap<Object, Object> parameters, String apiKey)  {
        StringBuffer stringBuffer = new StringBuffer();
        Set parameterKeys = parameters.entrySet();
        Iterator iterator = parameterKeys.iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = (Map.Entry) iterator.next();
            String key = (String) entry.getKey();
            Object value = entry.getValue();
            if (null != value && !"".equals(value) && !"sign".equals(key) && !"key".equals(key)) {
                stringBuffer.append(key + "=" + value + "&");
            }
        }

        stringBuffer.append("key=" + apiKey);
        String sign = encodeMD5(null, stringBuffer.toString()).toUpperCase();
        return sign;
    }

    /**
     * 生成微信支付xml格式参数列表
     * 
     * @param parameters
     */
    @SuppressWarnings("rawtypes")
    public static String buildRequestXml(SortedMap<Object, Object> parameters, String signString) {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("<xml>");
        Set entrySet = parameters.entrySet();
        Iterator iterator = entrySet.iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = (Map.Entry) iterator.next();
            String key = (String) entry.getKey();
            Object value = entry.getValue();
            if ("attach".equalsIgnoreCase(key) || "body".equalsIgnoreCase(key) || "sign".equalsIgnoreCase(key)) {
                stringBuffer.append("<" + key + ">" + "<![CDATA[" + value + "]]></" + key + ">");
            } else {
                stringBuffer.append("<" + key + ">" + value + "</" + key + ">");
            }
        }

        stringBuffer.append("<sign>" + signString + "</sign>");
        stringBuffer.append("</xml>");
        return stringBuffer.toString();
    }

    /**
     * 解析xml,返回第一级元素键值对。如果第一级元素有子节点，则此节点的值是子节点的xml数据。
     */
    public static Map<String, String> parseXmlToMap(String xml)  {
        try {
            return parseXmlToMap_0(xml);
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }

    private static Map<String, String> parseXmlToMap_0(String strXml) throws Throwable {
        strXml = strXml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\"");

        if (null == strXml || "".equals(strXml)) {
            return null;
        }
        Map<String, String> map = new HashMap<String, String>();

        InputStream inputStream = new ByteArrayInputStream(strXml.getBytes("UTF-8"));
        SAXBuilder builder = new SAXBuilder();
        // fix XML外部实体注入漏洞(XML External Entity Injection，简称 XXE)。
        // https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Prevention_Cheat_Sheet#C.2FC.2B.2B
        builder.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
        builder.setFeature("http://xml.org/sax/features/external-general-entities", false);
        builder.setFeature("http://xml.org/sax/features/external-parameter-entities", false);

        Document doc = builder.build(inputStream);
        Element root = doc.getRootElement();
        List list = root.getChildren();
        Iterator it = list.iterator();
        while (it.hasNext()) {
            Element e = (Element) it.next();
            String k = e.getName();
            String v = "";
            List children = e.getChildren();
            if (children.isEmpty()) {
                v = e.getTextNormalize();
            } else {
                v = WxpayXmlUtil.getChildrenText(children);
            }
            map.put(k, v);
        }

        // 关闭流
        inputStream.close();

        return map;
    }

    /**
     * 获取子结点的xml
     * 
     * @param children
     * @return String
     */
    @SuppressWarnings("rawtypes")
    public static String getChildrenText(List children) {
        StringBuffer sb = new StringBuffer();
        if (!children.isEmpty()) {
            Iterator it = children.iterator();
            while (it.hasNext()) {
                Element e = (Element) it.next();
                String name = e.getName();
                String value = e.getTextNormalize();
                List list = e.getChildren();
                sb.append("<" + name + ">");
                if (!list.isEmpty()) {
                    sb.append(WxpayXmlUtil.getChildrenText(list));
                }
                sb.append(value);
                sb.append("</" + name + ">");
            }
        }

        return sb.toString();
    }
}
